package com.itheima.filter;
import com.itheima.util.CurrentHolder;
import com.itheima.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest)  req;
        HttpServletResponse response = (HttpServletResponse) resp;

        String url = request.getRequestURI().toString();//获取路径

        if (url.contains("/login")){
            log.info("登录请求，直接放行");
            filterChain.doFilter(request, response);
            return;
        }

        String jwt = request.getHeader("token");

        if (!StringUtils.hasLength(jwt)){
            log.info("获取到的JWT令牌为空，返回错误的结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        try {
            Claims claims = JwtUtils.parseJwt(jwt);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
        } catch (Exception e) {
           e.printStackTrace();
           log.info("解析令牌失败，返回错误结果");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        log.info("令牌合法， 放行");
        filterChain.doFilter(request, response);

        //清空当前线程绑定的id
        CurrentHolder.remove();



    }
}
